package com.tripreset.sdk

import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.RegexUtils
import com.tripreset.sdk.bk.CommonDataSource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class CollectContentActivity : AppCompatActivity() {



    private val dataSource = CommonDataSource()


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        when (intent?.action) {
            Intent.ACTION_SEND -> {
                val stringExtra = intent.getStringExtra(Intent.EXTRA_TEXT)
                val subject = intent.getStringExtra(Intent.EXTRA_SUBJECT)
                LogUtils.i("==================================>$subject")
                val matchesList = RegexUtils.getMatches(
                    "((http|ftp|https)://)(([a-zA-Z0-9\\._-]+\\.[a-zA-Z]{2,6})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\\&%_\\./-~-]*)?",
                    stringExtra
                )

                if (matchesList.isNullOrEmpty()) {
                    finish()
                    return
                }

                GlobalScope.launch {

                    val keyWord = matchesList.first()
                    val content = withContext(Dispatchers.IO) { dataSource.loadContent(
                        keyWord,
                        keyWord.contains("imfw.cn") || keyWord.contains("mafengwo") || keyWord.contains("ctrip.com")|| keyWord.contains("tuniu.com")
                    ) }
                    LogUtils.i( "=======================$content")

                    val coverUrl = if (content.images.isNotEmpty()) {
                        content.images.first()?.url
                    } else {
                        ""
                    }
                    LogUtils.i( "=======================$coverUrl")
                    finish()
                }

            }
            else -> {
                // Handle other intents, such as being started from the home screen
            }
        }

    }
}